// 数据服务层，提供数据获取和管理功能
import { mockUsers, mockDepartments } from './mockData';
import Logger from '../utils/Logger';

// 使用单例模式实现数据服务
class DataService {
  constructor() {
    Logger.info('DataService', '初始化数据服务');
    this.users = [...mockUsers];
    this.departments = [...mockDepartments];
  }

  /**
   * 获取所有用户列表
   * @returns {Promise<Array>} 用户列表
   */
  async getUserList() {
    try {
      // 模拟异步请求延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      Logger.info('DataService', '获取用户列表成功');
      return [...this.users]; // 返回副本，避免外部直接修改原始数据
    } catch (error) {
      Logger.error('DataService', '获取用户列表失败: ' + JSON.stringify(error));
      throw error;
    }
  }

  /**
   * 根据ID获取用户信息
   * @param {string} id - 用户ID
   * @returns {Promise<Object|null>} 用户信息或null
   */
  async getUserById(id) {
    try {
      await new Promise(resolve => setTimeout(resolve, 100));
      const user = this.users.find(u => u.id === id);
      Logger.info('DataService', `获取用户ID:${id} ${user ? '成功' : '失败'}`);
      return user ? { ...user } : null;
    } catch (error) {
      Logger.error('DataService', `获取用户ID:${id} 失败: ` + JSON.stringify(error));
      throw error;
    }
  }

  /**
   * 获取所有部门列表
   * @returns {Promise<Array>} 部门列表
   */
  async getDepartmentList() {
    try {
      await new Promise(resolve => setTimeout(resolve, 200));
      Logger.info('DataService', '获取部门列表成功');
      return [...this.departments];
    } catch (error) {
      Logger.error('DataService', '获取部门列表失败: ' + JSON.stringify(error));
      throw error;
    }
  }

  /**
   * 根据部门名称筛选用户
   * @param {string} departmentName - 部门名称
   * @returns {Promise<Array>} 筛选后的用户列表
   */
  async getUserListByDepartment(departmentName) {
    try {
      await new Promise(resolve => setTimeout(resolve, 250));
      const filteredUsers = this.users.filter(u => u.department === departmentName);
      Logger.info('DataService', `获取部门${departmentName}的用户列表成功，共${filteredUsers.length}条`);
      return [...filteredUsers];
    } catch (error) {
      Logger.error('DataService', `获取部门${departmentName}的用户列表失败: ` + JSON.stringify(error));
      throw error;
    }
  }

  /**
   * 新增用户
   * @param {Object} user - 用户信息
   * @returns {Promise<Object>} 新增后的用户信息
   */
  async addUser(user) {
    try {
      await new Promise(resolve => setTimeout(resolve, 300));
      const newUser = {
        ...user,
        id: Date.now().toString() // 生成简单的ID
      };
      this.users.push(newUser);
      Logger.info('DataService', `新增用户${user.name}成功`);
      return { ...newUser };
    } catch (error) {
      Logger.error('DataService', `新增用户失败: ` + JSON.stringify(error));
      throw error;
    }
  }

  /**
   * 更新用户信息
   * @param {string} id - 用户ID
   * @param {Object} updates - 更新的字段
   * @returns {Promise<Object|null>} 更新后的用户信息或null
   */
  async updateUser(id, updates) {
    try {
      await new Promise(resolve => setTimeout(resolve, 300));
      const index = this.users.findIndex(u => u.id === id);
      if (index === -1) {
        Logger.warn('DataService', `更新用户失败，ID:${id}不存在`);
        return null;
      }
      
      this.users[index] = {
        ...this.users[index],
        ...updates
      };
      
      Logger.info('DataService', `更新用户ID:${id}成功`);
      return { ...this.users[index] };
    } catch (error) {
      Logger.error('DataService', `更新用户ID:${id}失败: ` + JSON.stringify(error));
      throw error;
    }
  }

  /**
   * 删除用户
   * @param {string} id - 用户ID
   * @returns {Promise<boolean>} 删除是否成功
   */
  async deleteUser(id) {
    try {
      await new Promise(resolve => setTimeout(resolve, 300));
      const initialLength = this.users.length;
      this.users = this.users.filter(u => u.id !== id);
      const success = this.users.length < initialLength;
      
      if (success) {
        Logger.info('DataService', `删除用户ID:${id}成功`);
      } else {
        Logger.warn('DataService', `删除用户失败，ID:${id}不存在`);
      }
      
      return success;
    } catch (error) {
      Logger.error('DataService', `删除用户ID:${id}失败: ` + JSON.stringify(error));
      throw error;
    }
  }
}

// 单例实例
let dataServiceInstance = null;

/**
 * 获取数据服务实例
 * @returns {DataService} 数据服务单例
 */
export function getDataService() {
  if (!dataServiceInstance) {
    dataServiceInstance = new DataService();
  }
  return dataServiceInstance;
}